package com.wans.guli.order.config;

import cn.hutool.core.util.ObjectUtil;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLevel() {
        return Logger.Level.FULL;
    }

    // 配置feign请求头信息 - 过滤器
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) (RequestContextHolder.getRequestAttributes());
                if (ObjectUtil.isNotEmpty(servletRequestAttributes)) {
                    // 线程上下文请求属性不为空
                    assert servletRequestAttributes != null; // 断言 - 这里不可能为空 （getRequest()）idea判断太烦加一行代码
                    HttpServletRequest request = servletRequestAttributes.getRequest();
                    // 获取请求头信息 - 设置到feign里
                    requestTemplate.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }
}
